package com.bootdo.fx.service.impl;

import com.bootdo.common.utils.IdWorker;
import com.bootdo.fx.dao.*;
import com.bootdo.fx.domain.*;
import com.bootdo.fx.service.DistributionRuleSetupService;
import com.bootdo.fx.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.bootdo.fx.service.OrderInfoService;
import org.springframework.transaction.annotation.Transactional;


@Service
public class OrderInfoServiceImpl implements OrderInfoService {
    @Autowired
    private OrderInfoDao orderInfoDao;

    @Autowired
    private DistributionRuleSetupDao distributionRuleSetupDao;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private UserInfoDao userInfoDao;

    @Autowired
    private GoodsInfoDao goodsInfoDao;

    @Autowired
    private OrderItemDao orderItemDao;

    @Autowired
    private UserShopCartDao userShopCartDao;

    @Autowired
    private UserAddressDao userAddressDao;

    @Autowired
    private UserFundsInfoDao userFundsInfoDao;


    @Override
    public OrderInfoDO get(Long orderId) {
        return orderInfoDao.get(orderId);
    }

    @Override
    public List<OrderInfoDO> list(Map<String, Object> map) {
        return orderInfoDao.list(map);
    }

    @Override
    public int count(Map<String, Object> map) {
        return orderInfoDao.count(map);
    }

    @Override
    public int save(OrderInfoDO orderInfo) {
        return orderInfoDao.save(orderInfo);
    }

    @Override
    public int update(OrderInfoDO orderInfo) {
        return orderInfoDao.update(orderInfo);
    }

    @Override
    public int remove(Long orderId) {
        return orderInfoDao.remove(orderId);
    }

    @Override
    public int batchRemove(Long[] orderIds) {
        return orderInfoDao.batchRemove(orderIds);
    }

    @Override
    public int ship(OrderInfoDO orderInfo) {
        return orderInfoDao.ship(orderInfo);
    }


    @Override
    @Transactional
    public boolean submitOrder(OrderInfoDO orderInfo, UserInfoDO userInfo, String shopCertIds, String addressId) {
        orderInfo.setOrderId(String.valueOf(idWorker.nextId()));
        orderInfo.setOrderSerialNo(String.valueOf(System.currentTimeMillis()));
        String[] certIds = shopCertIds.split(",");
        double amount = 0.00;
        for (String certId : certIds) {
            UserShopCartDO userShopCart = userShopCartDao.get(Long.parseLong(certId));
            double total = Double.parseDouble(String.valueOf(userShopCart.getCartQuantity()))
                    * Double.parseDouble(String.valueOf(userShopCart.getGoodsPrice()));
            amount += total;
            OrderItemDO orderItem = new OrderItemDO();
            orderItem.setItemId(idWorker.nextId());
            orderItem.setItemAmount(new BigDecimal(total));
            orderItem.setGoodsId(userShopCart.getGoodsId());
            orderItem.setGoodsName(userShopCart.getGoodsName());
            orderItem.setGoodsOriginPrice(userShopCart.getGoodsOriginPrice());
            orderItem.setGoodsQuantity(userShopCart.getCartQuantity());
            orderItem.setGoodsPrice(userShopCart.getGoodsPrice());
            orderItem.setOrderId(String.valueOf(orderInfo.getOrderId()));
            orderItem.setItemCreateTime(new Date());
            orderItem.setGoodsPicUrl(userShopCart.getGoodsPicUrll());
            orderItemDao.save(orderItem);
            userShopCartDao.remove(Long.parseLong(certId));
        }
        orderInfo.setOrderAmount(new BigDecimal(amount));
        orderInfo.setOrderCreateTime(new Date());
        orderInfo.setUserId(String.valueOf(userInfo.getUserId()));
        orderInfo.setUserOpenid(userInfo.getUserOpenid());
        orderInfo.setOrderPayStatus(0);
        orderInfo.setOrderStatus(0);
        orderInfo.setUserNickname(userInfo.getUserNickname());
        orderInfo.setIsBalance("0");
        UserAddressDO userAddress = userAddressDao.get(Long.parseLong(addressId));
        String detailAddr = userAddress.getAddrProvince() + "_" +
                userAddress.getAddrCity() + "_" +
                userAddress.getAddrArea() + ",详细地址：" +
                userAddress.getAddrAddress();
        orderInfo.setOrderAddress(detailAddr);
        int num = orderInfoDao.save(orderInfo);
        if (num > 0) {
            return true;
        } else {
            return false;
        }
    }

    @Transactional
    public OrderInfoDO buyOrder(OrderInfoDO orderInfo, UserInfoDO userInfo, String goodId, String num) {
        orderInfo.setOrderId(String.valueOf(idWorker.nextId()));
        orderInfo.setOrderSerialNo(String.valueOf(System.currentTimeMillis()));
        double amount = 0.00;

        GoodsInfoDO good = goodsInfoDao.get(Long.parseLong(goodId));
        if(num == null){
            num = "1";
        }
        double total = Double.parseDouble(num)
                * Double.parseDouble(String.valueOf(good.getGoodsPrice()));
        amount += total;
        OrderItemDO orderItem = new OrderItemDO();
        orderItem.setItemId(idWorker.nextId());
        orderItem.setItemAmount(new BigDecimal(total));
        orderItem.setGoodsId(good.getGoodsId());
        orderItem.setGoodsName(good.getGoodsGoodsName());
        orderItem.setGoodsOriginPrice(good.getGoodsOriginPrice());
        orderItem.setGoodsQuantity(Integer.parseInt(num));
        orderItem.setGoodsPrice(good.getGoodsPrice());
        orderItem.setOrderId(String.valueOf(orderInfo.getOrderId()));
        orderItem.setItemCreateTime(new Date());
        orderItem.setGoodsPicUrl(good.getGoodsPicUrl());
        orderItemDao.save(orderItem);

        orderInfo.setOrderAmount(new BigDecimal(amount));
        orderInfo.setOrderCreateTime(new Date());
        orderInfo.setUserId(String.valueOf(userInfo.getUserId()));
        orderInfo.setUserOpenid(userInfo.getUserOpenid());
        orderInfo.setOrderPayStatus(0);
        orderInfo.setOrderStatus(0);
        orderInfo.setUserNickname(userInfo.getUserNickname());
        orderInfo.setIsBalance("0");
        /*UserAddressDO userAddress = userAddressDao.get(Long.parseLong(addressId));
        String detailAddr = userAddress.getAddrProvince() + "_" +
                userAddress.getAddrCity() + "_" +
                userAddress.getAddrArea() + ",详细地址：" +
                userAddress.getAddrAddress();
        orderInfo.setOrderAddress(detailAddr);*/
        int n = orderInfoDao.save(orderInfo);
        if (n > 0) {
            return orderInfo;
        } else {
            return null;
        }
    }


    @Override
    @Transactional
    public OrderInfoDO submitOrder2(OrderInfoDO orderInfo, UserInfoDO userInfo, String shopCertIds) {
        orderInfo.setOrderId(String.valueOf(idWorker.nextId()));
        orderInfo.setOrderSerialNo(String.valueOf(System.currentTimeMillis()));
        String[] certIds = shopCertIds.split(",");
        double amount = 0.00;
        for (String certId : certIds) {
            UserShopCartDO userShopCart = userShopCartDao.get(Long.parseLong(certId));
            double total = Double.parseDouble(String.valueOf(userShopCart.getCartQuantity()))
                    * Double.parseDouble(String.valueOf(userShopCart.getGoodsPrice()));
            amount += total;
            OrderItemDO orderItem = new OrderItemDO();
            orderItem.setItemId(idWorker.nextId());
            orderItem.setItemAmount(new BigDecimal(total));
            orderItem.setGoodsId(userShopCart.getGoodsId());
            orderItem.setGoodsName(userShopCart.getGoodsName());
            orderItem.setGoodsOriginPrice(userShopCart.getGoodsOriginPrice());
            orderItem.setGoodsQuantity(userShopCart.getCartQuantity());
            orderItem.setGoodsPrice(userShopCart.getGoodsPrice());
            orderItem.setOrderId(String.valueOf(orderInfo.getOrderId()));
            orderItem.setItemCreateTime(new Date());
            orderItem.setGoodsPicUrl(userShopCart.getGoodsPicUrll());
            orderItemDao.save(orderItem);
            userShopCartDao.remove(Long.parseLong(certId));
        }
        orderInfo.setOrderAmount(new BigDecimal(amount));
        orderInfo.setOrderCreateTime(new Date());
        orderInfo.setUserId(String.valueOf(userInfo.getUserId()));
        orderInfo.setUserOpenid(userInfo.getUserOpenid());
        orderInfo.setOrderPayStatus(0);
        orderInfo.setOrderStatus(0);
        orderInfo.setUserNickname(userInfo.getUserNickname());
        orderInfo.setIsBalance("0");
       /* UserAddressDO userAddress = userAddressDao.get(Long.parseLong(addressId));
        String detailAddr = userAddress.getAddrProvince() + "_" +
                userAddress.getAddrCity() + "_" +
                userAddress.getAddrArea() + ",详细地址：" +
                userAddress.getAddrAddress();
        orderInfo.setOrderAddress(detailAddr);*/
        int num = orderInfoDao.save(orderInfo);
        if (num > 0) {
            return orderInfo;
        } else {
            return null;
        }
    }



    @Override
    public List<Map<String, Object>> listOrders(Map<String, Object> map) {
        return orderInfoDao.listOrders(map);
    }

    //@Scheduled(fixedRate=10000)
    @Transactional
    public void aotuBalanceOrders() {
        Map<String, Object> map = new HashMap<>();
        map.put("isBalance", 0);
        map.put("orderPayStatus", 1);
        List<OrderInfoDO> list = orderInfoDao.list(map);
        DistributionRuleSetupDO dd = distributionRuleSetupDao.list(null).get(0);
        for (OrderInfoDO order : list) {
            double sum = 0.0;
            UserInfoDO userinfo = userInfoDao.get(Long.parseLong(order.getUserId()));
            if(order.getOrderAmount() != null) {
                sum = order.getOrderAmount().doubleValue();
            }
            BigDecimal bigSum = new BigDecimal(sum);
            if(dd != null && sum != 0.0 && userinfo != null){
                long userId1 = userinfo.getUpUserId();
                BigDecimal first = null;
                BigDecimal second = null;
                BigDecimal third = null;
                if(dd.getCommissionScaleType() == 0) {
                    first = dd.getFirstLevelCommission().multiply(bigSum);
                    second = dd.getSecondLevelCommission().multiply(bigSum);
                    third = dd.getThirdLevelCommission().multiply(bigSum);
                }else{
                    first = dd.getFirstLevelCommission();
                    second = dd.getSecondLevelCommission();
                    third = dd.getThirdLevelCommission();
                }
                //找到一级会员
                if(userId1 != 0){
                    UserInfoDO userinfo1 = userInfoDao.get(userId1);
                    Map<String,Object> map1 = new HashMap<>();
                    map1.put("userId",userinfo1.getUserId());
                    UserFundsInfoDO userFundsInfoDO1 = userFundsInfoDao.list(map1).get(0);
                    userFundsInfoDO1.setFundsFirstSales(userFundsInfoDO1.getFundsFirstSales().add(bigSum));
                    userFundsInfoDO1.setFundsSalesSummary(userFundsInfoDO1.getFundsSalesSummary().add(bigSum));
                    userFundsInfoDO1.setFundsDistributionCommission(
                            userFundsInfoDO1.getFundsDistributionCommission().add(bigSum)
                    );
                    userFundsInfoDO1.setFundsWithdrawMoney(
                            userFundsInfoDO1.getFundsWithdrawMoney().add(first)
                    );
                    userFundsInfoDao.update(userFundsInfoDO1);
                    //找到二级会员
                    if(userinfo1.getUpUserId() != 0){
                        UserInfoDO userinfo2 = userInfoDao.get(userinfo1.getUpUserId());
                        Map<String,Object> map2 = new HashMap<>();
                        map2.put("userId",userinfo2.getUserId());
                        UserFundsInfoDO userFundsInfoDO2 = userFundsInfoDao.list(map2).get(0);
                        userFundsInfoDO2.setFundsSecondSales(userFundsInfoDO2.getFundsSecondSales().add(bigSum));
                        userFundsInfoDO2.setFundsSalesSummary(userFundsInfoDO2.getFundsSalesSummary().add(bigSum));
                        userFundsInfoDO2.setFundsDistributionCommission(
                                userFundsInfoDO2.getFundsDistributionCommission().add(bigSum)
                        );
                        userFundsInfoDO2.setFundsWithdrawMoney(
                                userFundsInfoDO2.getFundsWithdrawMoney().add(second)
                        );
                        userFundsInfoDao.update(userFundsInfoDO2);
                        //找到三级会员
                        if(userinfo2.getUpUserId() != 0){
                            UserInfoDO userinfo3 = userInfoDao.get(userinfo2.getUpUserId());
                            Map<String,Object> map3 = new HashMap<>();
                            map3.put("userId",userinfo3.getUserId());
                            UserFundsInfoDO userFundsInfoDO3 = userFundsInfoDao.list(map3).get(0);
                            userFundsInfoDO3.setFundsThirdSales(userFundsInfoDO3.getFundsThirdSales().add(bigSum));
                            userFundsInfoDO3.setFundsSalesSummary(userFundsInfoDO3.getFundsSalesSummary().add(bigSum));
                            userFundsInfoDO3.setFundsDistributionCommission(
                                    userFundsInfoDO3.getFundsDistributionCommission().add(bigSum)
                            );
                            userFundsInfoDO3.setFundsWithdrawMoney(
                                    userFundsInfoDO3.getFundsWithdrawMoney().add(third)
                            );
                            userFundsInfoDao.update(userFundsInfoDO3);
                        }else {
                            return;
                        }
                    }else{
                        return;
                    }
                order.setIsBalance("1");
                orderInfoDao.update(order);
                }else{
                    order.setIsBalance("1");
                    orderInfoDao.update(order);
                    return;
                }

            }else if(dd.getCommissionScaleType() == 1 && sum != 0.0 && userinfo != null){

            }else{
                return;
            }
        }
    }


}
